package com.gougou.manager.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gougou.manager.mapper.TbContentCategoryDao;
import com.gougou.manager.pojo.TbContentCategory;
import com.gougou.manager.service.MPTbContentCategoryService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 内容分类 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2018-09-07
 */
@Service
public class TbContentCategoryServiceImpl extends ServiceImpl<TbContentCategoryDao, TbContentCategory> implements MPTbContentCategoryService {

    /**
     * 删除所选中的内容类型
     * @param contentCategory
     */
    public void deleteAll(TbContentCategory contentCategory){


        List<TbContentCategory> ids = this.findAllSubNode(contentCategory.getParentId());
        EntityWrapper<TbContentCategory> wrapper = new EntityWrapper<TbContentCategory>();
        for (TbContentCategory category : ids){
            wrapper.where("id={0}",category.getId());
            super.delete(wrapper );
        }
        wrapper.where("parent_id={0}",contentCategory.getParentId());
        List<TbContentCategory> list = super.selectList(wrapper);
        if (null==list || list.isEmpty()){
            TbContentCategory parent = new TbContentCategory();
            parent.setId(contentCategory.getParentId());
            parent.setIsParent(0);
            super.updateById(parent);
        }

    }
    /**
     * 递归查找该节点下的所有子节点的id
     * @param pid
     */
    private List<TbContentCategory> findAllSubNode(Long pid){
        List<TbContentCategory> ids=new ArrayList<TbContentCategory>();
        EntityWrapper<TbContentCategory> wrapper = new EntityWrapper<TbContentCategory>();
        wrapper.where("parent_id={0}",pid);
        List<TbContentCategory> list =super.selectList(wrapper);
        for (TbContentCategory category : list){
            ids.add(category);
            if (category.getIsParent()==1){
                findAllSubNode(category.getId());
            }
        }
        return ids;
    }

}
